/**
 * 认证路由模块 - 需要认证Token的路由
 */

const express = require('express');
const multer = require('multer');
const authController = require('../controllers/authController');
const { authenticateToken } = require('../middlewares/authMiddleware');
const { validateFileContent, uploadWrapper, extractFileHash, parseUploadFields } = require('../middlewares/fileMiddleware');
const UploadService = require('../services/uploadService');
const { getLogger } = require('../logger');
const logger = getLogger('routes.authRoutes');
const config = require('../../config');
const { checkPermission, checkSelfOrPermission, checkPermissionLevel } = require('../middlewares/permissionMiddleware');

const router = express.Router();

// 所有用户路由都需要认证Token
router.use(authenticateToken);

// 自助类接口（仅认证）

// 上传头像 - 实现中间件链模式
router.post('/upload-avatar',
    extractFileHash(),
    // 使用uploadWrapper包装上传中间件，统一处理错误
    uploadWrapper((req, res, next) => {
        const userId = req.user.id;
        const uploadMiddleware = UploadService.createAvatarUploadMiddleware(userId);
        uploadMiddleware(req, res, next);
    }),
    // 文件内容验证中间件
    validateFileContent(config.upload.allowed.avatar, config.upload.limits.avatarMaxSize),
    // 控制器处理业务逻辑
    authController.uploadAvatar
);



// 上传文件 - 实现中间件链模式
router.post('/upload-file',
    checkPermission('file:upload'), checkPermissionLevel(40),
    // 使用uploadWrapper包装上传中间件，统一处理错误
    uploadWrapper((req, res, next) => {
        const userId = req.user.id;
        const uploadMiddleware = UploadService.createFileUploadMiddleware(userId);
        uploadMiddleware(req, res, next);
    }),
    // 文件内容验证中间件，使用默认配置
    validateFileContent(config.upload.allowed.file, config.upload.limits.fileMaxSize),
    // 控制器处理业务逻辑
    authController.uploadFile
);

// 大文件上传 - 实现中间件链模式
router.post('/upload-large-file',
    checkPermission('file:upload:large'), checkPermissionLevel(40),
    parseUploadFields(),
    extractFileHash(),
    (req, res, next) => {
        if (!req.fileHash) {
            logger.error('大文件上传缺少hash值', { userId: req.user?.id });
            return res.status(400).json({ message: '缺少文件哈希值' });
        }
        next();
    },
    // 然后使用带有正确fileHash的上传中间件处理chunk
    uploadWrapper((req, res, next) => {
        const uploadMiddleware = UploadService.createChunkUploadMiddleware(req.fileHash);
        uploadMiddleware(req, res, next);
    }),
    // 文件内容验证中间件，使用默认配置
    validateFileContent(config.upload.allowed.large, config.upload.limits.chunkMaxSize),
    // 控制器处理业务逻辑
    authController.uploadLargeFile
);

// 用户登出
router.post('/logout', authController.logout);


// 数据域类接口（通用接口，需要控制范围）



// 管理类接口（需要管理员权限）

// 强制登出用户（管理员功能）
router.post('/logout/:userId', checkPermission('online:force:logout'), checkPermissionLevel(40), authController.forceLogoutAllDevices);

// 使用sessionId强制登出用户（管理员功能）
router.post('/logout/session/:sessionId', checkPermission('online:force:logout'), checkPermissionLevel(40), authController.forceLogoutSessionuser);


// 获取用户Token状态
// router.get('/token-status/:userId', authController.getUserTokenStatus);

// 手动清理Token（管理员功能）
// router.post('/cleanup-tokens', authController.manualCleanupTokens);

// 获取Token统计
// router.get('/token-stats', authController.getTokenStats);

module.exports = router;